// 命令中间件接口
interface CommandMiddleware {
  execute<T>(command: ICommand<T>, next: () => Promise<T>): Promise<T>
}

// 中间件示例：权限校验
class AuthMiddleware implements CommandMiddleware {
  async execute<T>(command: ICommand<T>, next: () => Promise<T>) {
    if (!AuthManager.hasPermission(command.service, command.method)) {
      throw new Error('Unauthorized command')
    }
    return next()
  }
}

// 增强版执行器（支持中间件）
class AdvancedCommandExecutor {
  private middlewares: CommandMiddleware[] = []

  use(middleware: CommandMiddleware) {
    this.middlewares.push(middleware)
  }

  async execute<T>(command: ICommand<T>): Promise<T> {
    const chain = this.createExecutionChain(command)
    return chain()
  }

  private createExecutionChain<T>(command: ICommand<T>) {
    let index = -1
    const next = async () => {
      index++
      if (index >= this.middlewares.length) {
        return command.execute()
      }
      return this.middlewares[index].execute(command, next)
    }
    return next
  }
}
